import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


public class BT01 extends MIDlet implements CommandListener {
	private Display display;
	private Form form;
	private Command exit;
	private Command friendlyName;
	private Command btAddress;
	
	private String btAddressLocal;
	private String friendlyNameLocal;
	
	private LocalDevice localDevice;
	private RemoteDevice remoteDevice;
	
	private DiscoveryAgent agent;
	private RemoteDevice rd;

    // vetor com os dispositivos encontrados no inquiry
    public static Vector dispositivos = new Vector();
	
    public BT01() {
		form = new Form("Bluetooth 01");
		exit = new Command("Sair", Command.CANCEL, 0);
		friendlyName = new Command("Friendly Name", Command.OK, 1);
		btAddress = new Command("Bluetooth Address", Command.OK, 1);
		try {
			localDevice = LocalDevice.getLocalDevice();
		} catch (Exception e) {
			System.err.println(e);
		}
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		notifyDestroyed();
	}

	protected void pauseApp() {
	}

	protected void startApp() throws MIDletStateChangeException {
		display = Display.getDisplay(this);
		form.addCommand(exit);
		form.addCommand(friendlyName);
		form.addCommand(btAddress);
		form.setCommandListener(this);
		display.setCurrent(form);
	}

	public void commandAction(Command c, Displayable d) {
		if (c == exit) {
			try {
				destroyApp(true); // fecha a aplicacao
			} catch (MIDletStateChangeException e) {
				e.printStackTrace();
			}	
		} else if (c == friendlyName) {
			try {
				form.append(new StringItem(null, "Aguarde Localizando!!!"));

				dispositivos.removeAllElements();
				localDevice.setDiscoverable(DiscoveryAgent.GIAC);
				agent = localDevice.getDiscoveryAgent(); // obtain reference to singleton
				
	            boolean resultado = agent.startInquiry(DiscoveryAgent.GIAC, new BluetoothListener());
				
			} catch (BluetoothStateException e) {
				e.printStackTrace();
			}

		} else if (c == btAddress) {
			form.append(new StringItem(null, getBtAddressLocal()));
		}
	}
	
	public String getFriendlyNameLocal() {
		friendlyNameLocal = localDevice.getFriendlyName();
		return friendlyNameLocal;
	}
	
	public String getBtAddressLocal() {
		btAddressLocal = localDevice.getBluetoothAddress();
		return btAddressLocal;
	}
	
	public String getFriendlyNameRemote() {
		return null;
	}

	public String getBtAddressRemote() {
		return null;
	}
	
	public boolean buscaDispositivoRemoto() {
		try {
			agent = localDevice.getDiscoveryAgent();
		
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}
	
    class BluetoothListener implements DiscoveryListener {

		public void deviceDiscovered(RemoteDevice arg0, DeviceClass arg1) {
			if (!dispositivos.contains(remoteDevice)) {
				dispositivos.addElement(remoteDevice);
			}
		}

		public void inquiryCompleted(int arg0) {
	        
	        if ( dispositivos.size() == 0 ) {
				form.append(new StringItem(null, dispositivos.size() + " dispositivos encontrado"));
	        } else {
				form.append(new StringItem(null, "Nenhum encontrado"));
	        }
	        
		}

		public void serviceSearchCompleted(int arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}

		public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
			// TODO Auto-generated method stub
			
		}
    	
    }
}
